package top.yamhk.plugin.dynamic;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * agent
 * implements Cloneable
 *
 * @author yamhk
 */
@Slf4j
@RestController
@RequestMapping
public class ReMockApiAtDev {


    @Value("${url.localhost.mockRedirect:://12.99.142.142:55055}")
    private String mockRedirect;
    @Value("${url.localhost.mockAccess:/activity/m/{id}}")
    private String mockAccess;

    @GetMapping("/ac/view")
    public Object doView(
            @PathVariable(value = "id", required = false) String id
            , @RequestParam(required = false) Map<String, String> requestParam
    ) {
        String acId = !StringUtils.isEmpty(id) ? id : requestParam.get("id");
        String url = getTargetUrl(acId, requestParam);
        log.warn("url:{}", url);
        String body = HttpRequest.get(url)
                .form(new HashMap<>(requestParam))
                .execute()
                .body();
        return doRedirectBody(body);
    }

    @PostMapping("/ac/join")
    public Object doJoin(
            @PathVariable(value = "id", required = false) String id,
            @RequestBody(required = false) Map<String, String> requestParam
    ) {
        String acId = !StringUtils.isEmpty(id) ? id : requestParam.get("id");
        String url = getTargetUrl(acId, requestParam);
        String body = HttpRequest.post(url)
                .body(JSONUtil.toJsonStr(requestParam))
                .execute()
                .body();
        return doRedirectBody(body);
    }

    private Object doRedirectBody(String body) {
        body = body.replaceAll("null", "\"\"");
        if (JSONUtil.isJsonObj(body)) {
//            return JSONUtil.toBean(body, TreeMap.class);
            return body;
        } else {
            return body;
        }
    }

    private String getTargetUrl(String id, Map<String, String> requestParam) {
        //host
        String requestHost = requestParam.get("requestHost");
        requestHost = StringUtils.isEmpty(requestHost) ? mockRedirect : requestHost;
        //access
        String requestUri = requestParam.get("requestAccess");
        requestUri = StringUtils.isEmpty(requestUri) ? mockAccess : requestUri;
        //url
        return "http" + requestHost + requestUri.replace("{id}", StringUtils.isEmpty(id) ? "1" : id);
    }
}
